<template>
  <div class="new-room" v-if="visible" @click="show">
    <div @click.stop>
      <div class="new-room-left">
        <div class="new-room-left-head">
          <el-input placeholder="搜索" v-model="input" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <div class="new-room-left-bottom">
          <label class="new-room-left-bottom-item" v-if="currentUser.id !== user.id" v-for="user in users" :key="user.id">
            <input type="checkbox" v-model="checkedUsers" :value="user" name="user">
            <span class="checkmark"></span>
            <img :src="user.avatar" class="new-room-left-bottom-item-avatar">
            <span class="new-room-left-bottom-item-name">{{user.comment}}</span>
          </label>
        </div>
      </div>
      <div class="new-room-right">
        <div class="new-room-right-head">
          <span class="new-room-right-head-left" v-if="type !== 2">选择联系人</span>
          <span class="new-room-right-head-left" v-else>删除成员</span>
          <span class="new-room-right-head-right" v-if="checkedUsers.length>0">已选择{{checkedUsers.length}}个联系人</span>
        </div>
        <div class="new-room-right-mid">
          <div class="new-room-right-mid-item" v-for="user in checkedUsers" :key="user.id">
            <img :src="user.avatar" :title="user.comment">
            <span @click="unSelect(user)">x</span>
          </div>
        </div>
        <div class="new-room-right-bottom">
          <el-button type="success" @click="handleFinish">完成</el-button>
          <el-button type="success" @click="show" plain>取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'NewRoom',
  props: {
    users: {
      type: Array,
      required: true
    },
    type: {
      type: Number,
      required: true
    }
  },
  created () {
  },
  data () {
    return {
      input: '',
      visible: false,
      currentUser: this.$store.state.currentUser,
      checkedUsers: []
    }
  },
  methods: {
    show () {
      this.checkedUsers = []
      this.visible = !this.visible
    },
    hide () {
      this.visible = false
    },
    handleFinish () {
      if (this.$props.type === 0) {
        this.startRoomChat()
      } else if (this.$props.type === 1) {
        this.addMember()
      } else if (this.$props.type === 2) {
        this.deleteMember()
      }
    },
    // 拉群成员
    addMember () {
      const loading = this.$loading({
        target: '.container',
        text: '执行中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })

      let selecedConversation = this.$store.state.selectedConversation
      let groupId = selecedConversation.id
      let userIdList = this.userIds
      let params = new URLSearchParams()
      params.append('groupId', groupId)
      params.append('userIdList', userIdList)
      this.axios.post('/api/v1/group-member/add-new-member', params).then((response) => {
        if (response.data.code === 1) {
          this.visible = false
          selecedConversation.memberNumber = selecedConversation.memberNumber + userIdList.length
          selecedConversation.avatar = response.data.data
          this.$store.commit('updateConversation', selecedConversation)
        } else {
          this.$message.error(response.data.message)
          console.error(response.data.message)
        }
        loading.close()
      }).catch((error) => {
        loading.close()
        this.$message.error(error)
        console.log(error)
      })
    },
    // 踢群成员
    deleteMember () {
      const loading = this.$loading({
        target: '.container',
        text: '执行中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })

      let selecedConversation = this.$store.state.selectedConversation
      let groupId = selecedConversation.id
      let userIdList = this.userIds
      let params = new URLSearchParams()
      params.append('groupId', groupId)
      params.append('userIdList', userIdList)
      this.axios.post('/api/v1/group-member/delete-member', params).then((response) => {
        if (response.data.code === 1) {
          this.visible = false
          selecedConversation.memberNumber = selecedConversation.memberNumber - userIdList.length
          selecedConversation.avatar = response.data.data
          this.$store.commit('updateConversation', selecedConversation)
        } else {
          this.$message.error(response.data.message)
          console.error(response.data.message)
        }
        loading.close()
      }).catch((error) => {
        loading.close()
        this.$message.error(error)
        console.log(error)
      })
    },
    startRoomChat () {
      let groupMemberIdList = this.userIds
      // 2人不可建群
      if (groupMemberIdList.length === 1) {
        return
      }

      const loading = this.$loading({
        target: '.container',
        text: '执行中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })

      let groupName = this.chatRoomName
      let params = new URLSearchParams()
      params.append('groupMemberIdList', groupMemberIdList)
      params.append('groupName', groupName)

      this.axios.post('/api/v1/group/add-new', params).then((response) => {
        if (response.data.code === 1) {
          this.visible = false
          let senderId = response.data.data.id
          let avatar = response.data.data.groupAvatar
          let message = {senderId, avatar, comment: this.chatRoomName}
          this.addConversation(message)
        } else {
          this.$message({
            message: response.data.message,
            type: 'error'
          })
        }
        loading.close()
      }).catch((error) => {
        loading.close()
        this.$message({
          message: error,
          type: 'error'
        })
        console.log(error)
      })
    },
    // 添加会话
    addConversation (message) {
      let conversation = {
        id: message.senderId,
        avatar: message.avatar,
        comment: message.comment,
        chatType: 1,
        memberNumber: this.checkedUsers.length + 1, // 群的成员人数
        unreadMsgSum: 0,
        input: '',
        content: '',
        messages: []
      }
      let conversations = this.$store.state.conversations
      conversations.unshift(conversation)
      this.$store.commit('setConversations', conversations)
      this.$store.commit('setSelectedConversation', conversation)
    },
    updateConversation (selectedConversation) {
      let conversations = this.$store.state.conversations
      let i = 0
      for (i = 0; i < conversations.length; i++) {
        if (conversations[i].id === selectedConversation.id) {
          break
        }
      }
      conversations[i] = selectedConversation
      this.$store.commit('setConversations', conversations)
      this.$store.commit('setSelectedConversation', selectedConversation)
    },
    unSelect (user) {
      let index = this.checkedUsers.indexOf(user)
      this.checkedUsers.splice(index, 1)
    }
  },
  computed: {
    chatRoomName () {
      let maxLength = 5
      let name = this.currentUser.nickname + '、'
      let checkedUsers = this.checkedUsers
      let length = checkedUsers.length > maxLength ? maxLength : checkedUsers.length
      for (let i = 0; i < length; i++) {
        name = name + checkedUsers[i].nickname
        console.log('checkedUsers[' + i + '].nickname' + checkedUsers[i].nickname + ' ' + checkedUsers[i].username)
        if (i < length - 1) {
          name = name + '、'
        }
      }

      return name
    },
    userIds () {
      let ids = []
      for (let i = 0; i < this.checkedUsers.length; i++) {
        ids.push(this.checkedUsers[i].id)
      }
      return ids
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.new-room
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  z-index 200
  &>div
    width 600px
    height 440px
    margin 0 auto
    margin-top 100px
    display flex
    background-color #ffffff
    border 1px solid #dadada
  &-left
    flex-basis 300px
    &-head
      padding 10px
    &-bottom
      height 380px
      overflow auto
      &::-webkit-scrollbar
        display none
      &-item
        display flex
        justify-content justify-content
        align-items center
        height 50px
        &:hover
          background-color #e8e7e7
        input[type="checkbox"]
          display:none
        /* 未选中状态样式 */
        & .checkmark
          display inline-block
          width 16px
          height 16px
          border 1px solid #ccc
          border-radius 50%
          margin-left 20px
          vertical-align middle
        /* 选中状态样式 */
        & input:checked + .checkmark
          background #5daf34
        &-avatar
          width 30px
          height 30px
          border-radius 4px
          margin-left 10px
        &-name
          font-size 13px
          margin-left 8px
  &-right
    flex-basis 300px
    &-head
      padding 10px
      &-left
        font-size 15px
      &-right
        margin-left 100px
        font-size 10px
        color #7f7f7f
    &-mid
      height 330px
      box-sizing border-box
      overflow auto
      &::-webkit-scrollbar
        display none
      &-item
        float left
        position relative
        height 40px
        margin 20px 29px
        &>img
          width 40px
          height 40px
          border-radius 4px
        &>span
          position absolute
          top -6px
          right -10px
          width 13px
          height 13px
          line-height 10px
          text-align center
          background-color #cccccc
          border-radius 50%
          color white
          font-size 13px
          &:hover
            cursor pointer
            background-color #999999
    &-bottom
      display flex
      justify-content space-evenly
      align-items center
      margin-top  5px
</style>
